package main

import (
	"flag"
	"fmt"
	"os"
	"path/filepath"

	//"os"
	"runtime"
	//"strings"
	"log"
	"time"

	config "csudata.com/zqpool/src/config"
	mgrhttp "csudata.com/zqpool/src/mgrhttp"
	poolserver "csudata.com/zqpool/src/poolserver"
)

func main() {
	var pDebug = flag.Bool("debug", false, "Enable debug mode")
	var pConfigFile = flag.String("conf", "zqpool.conf", "Specify configuration file name")
	var pLogLevel = flag.String("loglevel", "info", "Specify logger level")
	var pLogFile = flag.String("logfile", "", "Specify logfile, if not specified, it is zqpool.log")

	flag.Parse()
	log.SetFlags(log.Lshortfile | log.LstdFlags)

	if *pDebug {
		go debugRoutine()
	}

	var logFile = *pLogFile
	if logFile == "" {
		exeFile, err := os.Executable()
		if err != nil {
			fmt.Println(err)
		}
		exePath := filepath.Dir(exeFile)
		logFile = filepath.Join(exePath, "zqpool.log")
	}

	err := InitLogger(logFile, 10*1024*1024, 5, 180, *pLogLevel)
	if err != nil {
		log.Printf("Unable to initialize logger(%s, %s): %s\n", *pLogLevel, logFile, err.Error())
		os.Exit(1)
		return
	}

	err = config.LoadConfig(*pConfigFile)
	if err != nil {
		log.Printf("Load config file %s failed: %s\n", *pConfigFile, err.Error())
		os.Exit(1)
		return
	}

	go mgrhttp.StartHttpServer()

	var listenIp string
	if config.Get("listen_addr") == "*" {
		listenIp = ":" + config.Get("listen_port")
	} else {
		listenIp = config.Get("listen_addr") + ":" + config.Get("listen_port")
	}
	poolserver.StartServer(listenIp)
}

func debugRoutine() {
	for {
		<-time.After(2 * time.Second)
		fmt.Println(time.Now(), "NumGoroutine", runtime.NumGoroutine())
	}
}
